package com.juejin.www.controller;

import com.juejin.www.aspect.Log;
import com.juejin.www.aspect.Perm;
import com.juejin.www.model.DTO.ArticleDTO;
import com.juejin.www.model.DTO.PageDTO;
import com.juejin.www.model.DTO.Result;
import com.juejin.www.model.VO.ArticleVO;
import com.juejin.www.service.ArticleService;
import com.juejin.www.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author Jacky
 */
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping
    @Perm(permission = "article:read")
    public Result list(@RequestParam Integer currentPage,@RequestParam Integer pageSize){
        log.info("获取文章列表");
        PageDTO<ArticleVO> articles = articleService.list(currentPage, pageSize);
        return Result.success(articles);
    }

    @GetMapping("/{id}")
    @Perm(permission = "article:read")
    public Result read(@PathVariable Integer id,@RequestHeader("token") String jwt){
        Integer uid = null;
        if(jwt!=null){
            try{
                uid = JwtUtils.getIdByJWT(jwt);
            }catch (Exception e){
                uid=null;
            }
        }
        log.info("阅读{}号文章",id);
        ArticleVO article = articleService.read(id,uid);
        return Result.success(article);
    }

    @PostMapping("/viewCount/{id}")
    public Result addViewCount(@PathVariable Integer id){
        log.info("给{}号文章添加浏览量",id);
        articleService.addViewCount(id);
        return Result.success();
    }

    @Log
    @Perm(permission = "article:add")
    @PostMapping
    public Result add(@RequestBody ArticleDTO articleDTO,@RequestHeader("token") String jwt){
        Integer uid = JwtUtils.getIdByJWT(jwt);
        articleDTO.setAuthorId(uid);
        log.info("{}号用户发布文章",articleDTO.getAuthorId());
        articleService.addArticle(articleDTO);
        return Result.success();
    }

    @Log
    @Perm(permission = "article:delete")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        log.info("删除{}号文章",id);
        articleService.deleteArticle(id);
        return Result.success();
    }
}
